package com.github.ecbp.user.service.config;

import com.alibaba.fastjson.JSON;
import com.github.ecbp.common.constant.CacheKeyConstant;
import com.github.ecbp.common.redis.RedisUtil;
import com.github.ecbp.common.security.vo.DefaultSecurityConfig;
import com.github.ecbp.user.service.response.ResourceRes;
import com.github.ecbp.user.service.service.ResourceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * mall-security模块相关配置
 */
@Component
public class AdminSecurityConfig {

    Logger logger = LoggerFactory.getLogger(AdminSecurityConfig.class);

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ResourceService resourceService;

    @PostConstruct
    public void initSecurityService() {
        this.reloadTotalPermission();
    }

    public Map<String, DefaultSecurityConfig> reloadTotalPermission() {
        Map<String, DefaultSecurityConfig> configAttributeMap = new HashMap<>();
        Set<ResourceRes> resourceList = resourceService.listAll();
        for (ResourceRes resource : resourceList) {
            if (/*resource.getPermissionStatus() && */null != resource.getPermissionId()) {
                configAttributeMap.put(
                        resource.getProjectName() + CacheKeyConstant.PATH_SEPARATOR + resource.getUrl(),
                        new DefaultSecurityConfig(resource.getPermissionPower())
                );
            }
        }
        logger.info("系统权限 {}", configAttributeMap.size());
        redisUtil.set(CacheKeyConstant.SECURITY_KEY, JSON.toJSONString(configAttributeMap), 1);
        return configAttributeMap;
    }
}
